package 链表;

import java.util.HashMap;

/**
 * @author: TTDB
 * @create: 2025/9/17
 */
public class copyRandomList {
    //创建一个HashMap来存储Random节点-------------关键点
    public Node copyRandomList(Node head) {
        if(head == null) return null;
        Node cur = head;
        //构建Hash索引来存储Random节点
        HashMap<Node,Node> map = new HashMap<>();
        while(cur!=null){
            map.put(cur,new Node(cur.val));
            cur = cur.next;
        }
        cur = head;
        while(cur!=null){
            map.get(cur).next = map.get(cur.next);
            map.get(cur).random = map.get(cur.random);
            cur = cur.next;
        }
        return map.get(head);
    }
    class Node {
        int val;
        Node next, random;
        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }

}
